package com.smilive.delay.queue.redis;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

/**
 * @program: delay_queue_start
 * @Date: 2022-02-08 14:50
 * @Author: smilive
 * @Description: https://blog.52itstyle.vip/archives/5163/
 */
@Slf4j
public class RedisDelayQueue {

    private static final DateTimeFormatter F = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) throws InterruptedException {

        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379")
                .setPassword("smilive").setDatabase(1);
        RedissonClient redissonClient = Redisson.create(config);

        //延迟任务 目标队列
        RBlockingDeque<RedisDelayTask> queue = redissonClient.getBlockingDeque("redisDelayQueue");
        //延迟任务将到期的元素转移到目标队列
        RDelayedQueue<RedisDelayTask> delayedRedPacketQueue = redissonClient.getDelayedQueue(queue);

        for (int i = 1; i <= 5; i++) {
            delayedRedPacketQueue.offer(new RedisDelayTask(i), i,TimeUnit.SECONDS);
        }

        while (true){
            RedisDelayTask take = queue.take();
            log.info("任务执行时间:{},任务创建时间:{},任务ID:{}",
                    LocalDateTime.now().format(F),
                    LocalDateTime.ofInstant(Instant.ofEpochMilli(take.getTimestamp()), ZoneId.systemDefault()).format(F),
                    take.getTaskId());
        }

    }
}
